package edu.gxmzu.task.controller;

import edu.gxmzu.task.filter.JwtAuthenticationTokenFilter;
import edu.gxmzu.task.params.LoginParam;
import edu.gxmzu.task.service.AccountsService;
import edu.gxmzu.task.utils.JWTUtil;
import edu.gxmzu.task.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Tag(name = "登录注册模块", description = "用户认证授权相关操作")
@RestController
@Slf4j
public class LoginController {
    @Resource
    private AccountsService accountService;
    @Operation(summary = "登录", description = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam) throws Exception {
        return accountService.login(loginParam.getUsername(), loginParam.getPassword());
    }
    @Operation(summary = "注册")
    @PostMapping("/register")
    public Result register(@RequestBody LoginParam loginParam) throws Exception {
       return accountService.register(loginParam.getUsername(), loginParam.getPassword(), loginParam.getName(), loginParam.getEmail(), loginParam.getRole());
    }
    @Operation(summary = "退出登录")
    @PostMapping("/lout")  // 使用logout会被security强制重定向至 /logout?logout
    @PreAuthorize("hasAuthority('user') or hasAuthority('admin')")  // 资源所需权限
    public Result logout(HttpServletRequest request) throws Exception {
//        String token = request.getHeader(JwtAuthenticationTokenFilter.TOKEN_KEY);
//        String userId = JWTUtil.getUserIdFromToken(token);
      return accountService.logout();
    }
    @Operation(summary = "注销账号")
    @PutMapping("/deactivate")  // 使用logout会被security强制重定向至 /logout?logout
    @PreAuthorize("hasAuthority('user') or hasAuthority('admin')")  // 资源所需权限
    public Result deactivate(HttpServletRequest request) throws Exception {
        return accountService.deactivate(JWTUtil.getUserIdFromToken(request.getHeader(JwtAuthenticationTokenFilter.TOKEN_KEY)));
    }
}
